package com.liuxinlong.api;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.liuxinlong.common.AosException;
import com.liuxinlong.common.SnowFlake;
import com.liuxinlong.constant.SystemConstants;
import com.liuxinlong.enums.MessageContentTypeEnum;
import com.liuxinlong.enums.MessagePushBusinessEnum;
import com.liuxinlong.enums.MessagePushRecordStatusEnum;
import com.liuxinlong.enums.ReturnCodes;
import com.liuxinlong.modules.dao.FileManageDao;
import com.liuxinlong.modules.dao.MessagePushFailedLogDao;
import com.liuxinlong.modules.dao.ParameterDao;
import com.liuxinlong.modules.dao.UserDao;
import com.liuxinlong.modules.entity.FileManage;
import com.liuxinlong.modules.entity.MessageConfiguration;
import com.liuxinlong.modules.entity.MessagePushFailedLog;
import com.liuxinlong.modules.entity.MessagePushRecord;
import com.liuxinlong.modules.entity.SystemParameter;
import com.liuxinlong.utils.ObjectUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 企业微信消息推送服务器api
 *
 * @author liuxinlong@hotwater.com.cn
 * @version 1.0.0
 * @since 2022年12月28日
 */
@Service
@Slf4j
public class WeChatMessageService implements WeChatMessageInterface {

    public final static String ACCESS_TOKEN_URL = "https://qyapi.weixin.qq.com/cgi-bin/gettoken";

    public final static String TOKEN = "08668466-2b1f-4025-98b4-2b62cd1a294c";

    public final static String SEND_URL = "https://qyapi.weixin.qq.com/cgi-bin/message/send";

    public final static String CORP_ID = "wxcce3fac4a3c8b78c";

    public final static int AGENT_ID = 41;

    public final static String SECRET = "ZWCrt-orHpcJX-poGPC4SD17kApJvos56VerTHfIick";

    public final static String RECALL_URL = "https://qyapi.weixin.qq.com/cgi-bin/message/recall";

    public final static String UPLOAD_URL = "https://qyapi.weixin.qq.com/cgi-bin/media/upload";

    private static final String BOUNDARY = "******";

    private static final String PRE_FIX = ("\r\n--" + BOUNDARY + "\r\n");

    private static final String END_FIX = ("\r\n--" + BOUNDARY + "--\r\n");

    @Autowired
    private UserDao userDao;

    @Autowired
    private MessagePushFailedLogDao messagePushFailedLogDao;

    @Autowired
    private ParameterDao parameterDao;

    @Autowired
    private FileManageDao fileManageDao;

    @Override
    public MessagePushRecord pushMessage(List<String> userList, String recordId, MessageConfiguration messageConfiguration, String currentTime) {
        String messageId = messageConfiguration.getId();
        StringBuffer empIds = new StringBuffer();
        List<MessagePushFailedLog> sysFailedList = new ArrayList<>();
        Map<String, Map<String, String>> userEmpMap = userDao.getUserWechatMap();
        for (String uid : userList) {
            if (!userEmpMap.containsKey(uid)) {
                continue;
            }
            String userEmpId = userEmpMap.get(uid).get("empId");
            if (StringUtils.isEmpty(userEmpId)) {
                MessagePushFailedLog mfl = new MessagePushFailedLog();
                mfl.setId(SnowFlake.nextIdStr());
                mfl.setRecordId(recordId);
                mfl.setMessageId(messageId);
                mfl.setUserId(uid);
                mfl.setErrMsg("用户企业微信id不存在");
                sysFailedList.add(mfl);
                continue;
            }
            if (!StringUtils.isEmpty(empIds)) {
                empIds.append("|");
            }
            empIds.append(userEmpId);
        }
        HttpURLConnection httpUrlConn;
        String token = getAccessToken();
        StringBuffer buffer = new StringBuffer();
        MessagePushRecord messagePushRecord = new MessagePushRecord();

        try {
            String targetUrl = SEND_URL + "?access_token=" + token + "&debug=1";
//            String targetUrl = SEND_URL + "?access_token=" + token;
            URL url = new URL(targetUrl);
            //http协议传输
            httpUrlConn = (HttpURLConnection) url.openConnection();
            httpUrlConn.setRequestMethod("POST");
            httpUrlConn.setConnectTimeout(5000);
            httpUrlConn.setReadTimeout(5000);
            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);

            httpUrlConn.setRequestProperty("Accept", "application/json;odata=verbose");
            httpUrlConn.setRequestProperty("Connection", "keep-alive");
            httpUrlConn.setRequestProperty("Content-Type", "application/json;odata=verbose");
            httpUrlConn.setRequestProperty("Content-Length", "0");
            httpUrlConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36");
            httpUrlConn.setRequestProperty("charset", "UTF-8");

            Map<String, Object> param = buildParam(messageConfiguration, currentTime);
            param.put("touser", empIds);
//            param.put("toparty", "PartyID1|PartyID2");
//            param.put("totag", "TagID1 | TagID2");
            OutputStream os = httpUrlConn.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
            osw.write(JSONUtil.toJsonStr(param));
            osw.flush();
            osw.close();

//            httpUrlConn.setUseCaches(false);
            //必须设置false，否则会自动redirect到重定向后的地址
            httpUrlConn.setInstanceFollowRedirects(false);
            httpUrlConn.connect();

            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            //释放资源
            inputStream.close();
            httpUrlConn.disconnect();
            System.out.println("resp111: " + buffer.toString());
            Map<String, Object> resMap = JSONUtil.parseObj(buffer);

            messagePushRecord.setMsgId((String) resMap.get("msgid"));
            int errCode = (int) resMap.get("errcode");
            messagePushRecord.setErrCode(String.valueOf(errCode));
            messagePushRecord.setErrMsg((String) resMap.get("errmsg"));
            String invalidUser = (String) resMap.get("invaliduser");
            messagePushRecord.setInvalidUser(invalidUser);
            int allNum = userList.size();
            messagePushRecord.setAllNum(allNum);
            int failedNum = sysFailedList.size();
            if (errCode == 0) {
                List<String> failedList = StringUtils.isEmpty(invalidUser) ? new ArrayList<>() : Arrays.asList(invalidUser.split("\\|"));
                failedNum = failedNum + (ObjectUtils.isEmpty(failedList) ? 0 : failedList.size());
                if (!ObjectUtils.isEmpty(failedList)) {
                    Map<String, Map<String, String>> empUserMap = userDao.getWechatUserMap();
                    for (String emp : failedList) {
                        Map<String, String> map = empUserMap.get(emp);
                        MessagePushFailedLog mfl = new MessagePushFailedLog();
                        mfl.setId(SnowFlake.nextIdStr());
                        mfl.setRecordId(recordId);
                        mfl.setMessageId(messageId);
                        mfl.setUserId(map.get("id"));
                        mfl.setErrMsg("用户企业微信id无效");
                        sysFailedList.add(mfl);
                    }
                }
            } else {
                failedNum = userList.size();
            }
            messagePushRecord.setFailedNum(failedNum);
            messagePushRecord.setStatus(failedNum == 0 ? MessagePushRecordStatusEnum.ALL_SUCCESS.getValue() : failedNum == allNum ? MessagePushRecordStatusEnum.ALL_FAILED.getValue() : MessagePushRecordStatusEnum.PART_SUCCESS.getValue());

            if (!sysFailedList.isEmpty()) {
                messagePushFailedLogDao.insertBatch(sysFailedList);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return messagePushRecord;
    }

    @Override
    public void recallMessage(String msgId) {
        HttpURLConnection httpUrlConn;
        String token = getAccessToken();
        StringBuffer buffer = new StringBuffer();
        try {
            String targetUrl = RECALL_URL + "?access_token=" + token;
            URL url = new URL(targetUrl);
            //http协议传输
            httpUrlConn = (HttpURLConnection) url.openConnection();
            httpUrlConn.setRequestMethod("POST");
            httpUrlConn.setConnectTimeout(5000);
            httpUrlConn.setReadTimeout(5000);
            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);

            httpUrlConn.setRequestProperty("Accept", "application/json;odata=verbose");
            httpUrlConn.setRequestProperty("Connection", "keep-alive");
            httpUrlConn.setRequestProperty("Content-Type", "application/json;odata=verbose");
            httpUrlConn.setRequestProperty("Content-Length", "0");
            httpUrlConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36");
            httpUrlConn.setRequestProperty("charset", "UTF-8");


            Map<String, Object> param = new HashMap<>();
            param.put("msgid", msgId);
            OutputStream os = httpUrlConn.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
            osw.write(JSONUtil.toJsonStr(param));
            osw.flush();
            osw.close();

//            httpUrlConn.setUseCaches(false);
            //必须设置false，否则会自动redirect到重定向后的地址
            httpUrlConn.setInstanceFollowRedirects(false);
            httpUrlConn.connect();

            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            //释放资源
            inputStream.close();
            httpUrlConn.disconnect();
            System.out.println("resp222: " + buffer.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public String uploadTemplateMedia(String localPath) {
        HttpURLConnection httpUrlConn = null;
        String token = getAccessToken();
        StringBuffer buffer = new StringBuffer();
        String mediaId = "";
        try {
//            String targetUrl = UPLOAD_URL + "?access_token=" + token + "&type=image&debug=1";
            String targetUrl = UPLOAD_URL + "?access_token=" + token + "&type=image";
            URL url = new URL(targetUrl);
            //http协议传输
            httpUrlConn = (HttpURLConnection) url.openConnection();
            httpUrlConn.setConnectTimeout(5000);
            httpUrlConn.setReadTimeout(5000);
            httpUrlConn.setRequestMethod("POST");
//            httpUrlConn.setRequestProperty("Accept", "application/json;odata=verbose");
//            httpUrlConn.setRequestProperty("Connection", "keep-alive");
            httpUrlConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

            File file = new File(localPath);
            httpUrlConn.setRequestProperty("Content-Disposition", "form-data; name=media;filename=" + file.getName());
            httpUrlConn.setRequestProperty("Content-Length", String.valueOf(file.length()));
            httpUrlConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36");

            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            httpUrlConn.connect();

            OutputStream outputStream = httpUrlConn.getOutputStream();

            // 要上传的数据
            StringBuffer strBuf = new StringBuffer();
            // 标识payLoad + 文件流的起始位置
            strBuf.append(PRE_FIX);

            // 这里的Content-Type的类型需与上传文件类型一致。
            strBuf.append(
                    "Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"\r\n");
            strBuf.append("Content-Type: " + Files.probeContentType(file.toPath()) + "\r\n\r\n");
            outputStream.write(strBuf.toString().getBytes());

            // 获取文件流
            FileInputStream fileInputStream = new FileInputStream(file);
            DataInputStream inputStreamFile = new DataInputStream(fileInputStream);
            // 每次上传的大小
            byte[] bufferOut = new byte[4096];
            int b = -1;
            // 上传文件
            while ((b = inputStreamFile.read(bufferOut)) != -1) {
                outputStream.write(bufferOut, 0, b);
            }

            // 参数间需换行
            outputStream.write("\r\n".getBytes());
            //第二部分参数：其他参数promoId,operator
            // TODO 动态参数需自行定义 当前只是一个参数 name

            StringBuilder contentBody = new StringBuilder();
            contentBody.append(PRE_FIX);
            contentBody.append("Content-Disposition: form-data; name=\"name\"" + "\r\n");
            contentBody.append("\r\n");
//            contentBody.append(params);

            // 第二个参数
//            contentBody.append(PRE_FIX);
//            contentBody.append("Content-Disposition: form-data; name=\"age\"" + "\r\n");
//            contentBody.append("\r\n");
//            contentBody.append(params);

            outputStream.write(contentBody.toString().getBytes());
            outputStream.write(END_FIX.getBytes());

            outputStream.flush();
            outputStream.close();
//
//            FileInputStream fis = new FileInputStream(file);
//            OutputStream os = httpUrlConn.getOutputStream();
//            byte[] upBuffer = new byte[4096];
//            int len = 0;
//            while ((len = fis.read(upBuffer, 0, upBuffer.length)) != -1) {
//                os.write(upBuffer, 0, len);
//            }
//            os.flush();
//            os.close();

            int code = httpUrlConn.getResponseCode();
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            //释放资源
            inputStream.close();
            httpUrlConn.disconnect();

            JSONObject res = JSONUtil.parseObj(buffer);
            int errcode = (int) res.get("errcode");
            if (errcode == 0) {
                mediaId = (String) res.get("media_id");
            }
            log.info("res234", res);
            System.out.println("resp11111: " + buffer.toString());
            log.info("res111", buffer);
            log.info("文件上传成功");
            log.info("==========================");
        } catch (ConnectException e) {
            e.printStackTrace();
            throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR, e.getMessage());
        } catch (AosException e) {
            throw e;
        } catch (Exception e) {
            e.printStackTrace();
            throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR, e.getMessage());
        } finally {
            httpUrlConn.disconnect();
        }
        return mediaId;
    }

    private String getAccessToken() {
        HttpURLConnection httpUrlConn;
        String accessToken = "";
        StringBuffer buffer = new StringBuffer();
        try {
            String targetUrl = ACCESS_TOKEN_URL + "?corpid=" + CORP_ID + "&corpsecret=" + SECRET;
            URL url = new URL(targetUrl);

            //http协议传输
            httpUrlConn = (HttpURLConnection) url.openConnection();
            httpUrlConn.setConnectTimeout(5000);
            httpUrlConn.setReadTimeout(5000);
            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);

            httpUrlConn.setRequestMethod("GET");
//            httpUrlConn.setRequestProperty("corpid",CORP_ID);
//            httpUrlConn.setRequestProperty("corpsecret",SECRET);

            httpUrlConn.setUseCaches(false);
            //必须设置false，否则会自动redirect到重定向后的地址
            httpUrlConn.setInstanceFollowRedirects(false);
            httpUrlConn.connect();
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            //释放资源
            inputStream.close();
            httpUrlConn.disconnect();
            System.out.println("resp: " + buffer.toString());
            Map<String, Object> resMap = JSONUtil.parseObj(buffer);
            accessToken = (String) resMap.get("access_token");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return accessToken;
    }

    private Map<String, Object> buildParam(MessageConfiguration messageConfiguration, String currentTime) {
        String content = messageConfiguration.getContent();
        Map<String, Object> param = new HashMap<>();
        param.put("agentid", AGENT_ID);
        param.put("safe", 0);
        param.put("enable_id_trans", 0);
        param.put("enable_duplicate_check", 0);
        String jumpUrl = buildUrl(messageConfiguration);
//        String mediaId = "3Gl5-tUu-81V7bdc6hEk3fSL2-jRKo_KEO-JU0arj4_CyCtZStUW93RjQrWKlkRxa";
        String mediaId = "";
        String fileId = messageConfiguration.getMediaFile();
        if (StringUtils.isNotEmpty(fileId)) {
            FileManage fileManage = fileManageDao.selectById(fileId);
            if (!ObjectUtils.isEmpty(fileManage)) {
                mediaId = uploadTemplateMedia(fileManage.getFilePath());
            }
        }
        int contentType = messageConfiguration.getContentType();
        int businessType = messageConfiguration.getBusinessType();
        if (contentType == MessageContentTypeEnum.TEXT.getValue()) {
            param.put("msgtype", "text");
            Map<String, Object> text = new HashMap<>();
            text.put("content", content);
            param.put("text", text);
        } else if (contentType == MessageContentTypeEnum.IMAGE.getValue()) {
            param.put("msgtype", "image");
            Map<String, Object> image = new HashMap<>();
            image.put("media_id", mediaId);
            param.put("image", image);
        } else if (contentType == MessageContentTypeEnum.VOICE.getValue()) {
            param.put("msgtype", "voice");
            Map<String, Object> voice = new HashMap<>();
            voice.put("media_id", mediaId);
            param.put("voice", voice);
        } else if (contentType == MessageContentTypeEnum.VIDEO.getValue()) {
            param.put("msgtype", "video");
            Map<String, Object> video = new HashMap<>();
            video.put("media_id", mediaId);
            video.put("title", MessagePushBusinessEnum.getMsgTitleByValue(businessType));
            video.put("description", content);
            param.put("video", video);
        } else if (contentType == MessageContentTypeEnum.FILE.getValue()) {
            param.put("msgtype", "file");
            Map<String, Object> file = new HashMap<>();
            file.put("media_id", mediaId);
            param.put("file", file);
        } else if (contentType == MessageContentTypeEnum.TEXT_CARD.getValue()) {
            param.put("msgtype", "textcard");
            Map<String, Object> textCard = new HashMap<>();
            textCard.put("title", MessagePushBusinessEnum.getMsgTitleByValue(businessType));
            String shareUser = StringUtils.isEmpty(messageConfiguration.getShareUser()) ? "系统" : messageConfiguration.getShareUser();
            String despcription = "<div class=\"normal\">" + MessagePushBusinessEnum.getWechatNameByValue(messageConfiguration.getBusinessType()) +
                    "</div><div class=\"gray\">" + currentTime +
                    "</div> <div class=\"highlight\">" + messageConfiguration.getContent() +
                    "</div><div class=\"normal\">" + "创建人：" + shareUser + "</div>"
                    + (messageConfiguration.getTerminal() == 2 ? "" : "<div class=\"gray\">本条消息详情仅支持电脑端查看</div>");
            textCard.put("description", despcription);
            textCard.put("url", jumpUrl);
            textCard.put("btntxt", "登陆查看");
            param.put("textcard", textCard);
        } else if (contentType == MessageContentTypeEnum.IMAGE_TEXT.getValue()) {
            param.put("msgtype", "news");
            List<Map<String, Object>> articles = new ArrayList<>();
            Map<String, Object> article = new HashMap<>();
            article.put("title", MessagePushBusinessEnum.getMsgTitleByValue(businessType));
            article.put("description", content);
            article.put("url", jumpUrl);
            article.put("picurl", "http://res.mail.qq.com/node/ww/wwopenmng/images/independent/doc/test_pic_msg1.png");
            articles.add(article);
            param.put("news", articles);
        } else if (contentType == MessageContentTypeEnum.MP_NEWS.getValue()) {
            param.put("msgtype", "mpnews");
            String shareUser = StringUtils.isEmpty(messageConfiguration.getShareUser()) ? "系统" : messageConfiguration.getShareUser();
            Map<String, Object> mpNews = new HashMap<>();
            List<Map<String, Object>> articles = new ArrayList<>();
            Map<String, Object> article = new HashMap<>();
            article.put("title", MessagePushBusinessEnum.getMsgTitleByValue(businessType));
            article.put("thumb_media_id", mediaId);
            article.put("author", shareUser);
            article.put("content_source_url", jumpUrl);
//            article.put("content", content.replaceAll("\\\\n","<br/>"));
            article.put("content", "<pre> <div style=\"font-size:20px;color:black;font-family: 微软雅黑\">" +
                    content + "</div>" +
                    (messageConfiguration.getTerminal() == 2 ? "" : "<div class=\"gray\">本条消息详情仅支持电脑端查看</div>") + "</pre>");
            article.put("digest", MessagePushBusinessEnum.getNameByValue(messageConfiguration.getBusinessType()));
            articles.add(article);
//            Map<String, Object> article1 = new HashMap<>();
//            article1.put("title", "【RDKS提醒111】");
//            article1.put("thumb_media_id", mediaId);
//            article1.put("author", messageConfiguration.getShareUser());
//            article1.put("content_source_url", jumpUrl);
//            article1.put("content", content + "第二段");
//            article1.put("digest", MessagePushBusinessEnum.getNameByValue(messageConfiguration.getBusinessType()) + "<div class=\"gray\">本条消息详情仅支持电脑端查看</div>");
//            articles.add(article1);
            mpNews.put("articles", articles);
            param.put("mpnews", mpNews);
        } else if (contentType == MessageContentTypeEnum.MARK_DOWN.getValue()) {
            param.put("msgtype", "markdown");
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append("您有新消息，稍后会同步到`个人中心`\n");
            stringBuffer.append(">【RDKS提醒】\n");
            stringBuffer.append(">模 块：<font color=\"info\">");
            stringBuffer.append(MessagePushBusinessEnum.getWechatNameByValue(messageConfiguration.getBusinessType()));
            stringBuffer.append("</font> \n");

            stringBuffer.append(">时 间：<font color=\"comment\">");
            stringBuffer.append(currentTime);
            stringBuffer.append("</font> \n");

            stringBuffer.append("><font color=\"warning\">");
            stringBuffer.append(messageConfiguration.getContent());
            stringBuffer.append("</font> \n");

            stringBuffer.append(">创建人:<font color=\"info\">");
            stringBuffer.append(messageConfiguration.getShareUser());
            stringBuffer.append("</font>\n");

//                                >请准时参加会议。
//                                >
//                                >如需修改会议信息，请点击：[修改会议信息](https://work.weixin.qq.com)"
            Map<String, Object> markdown = new HashMap<>();
            markdown.put("content", stringBuffer.toString());
            param.put("markdown", markdown);
        } else if (contentType == MessageContentTypeEnum.MINI_PROGRAM_NOTICE.getValue()) {
            param.put("msgtype", "miniprogram_notice");
            Map<String, Object> miniProgram = new HashMap<>();
            miniProgram.put("appid", "wx123123123123123");
            miniProgram.put("page", "pages/index?userid=zhangsan&orderid=123123123");
            miniProgram.put("title", "会议室预订成功通知");
            miniProgram.put("description", "4月27日 16:16");
            miniProgram.put("emphasis_first_item", true);
            List<Map<String, Object>> contentIitems = new ArrayList<>();
            Map<String, Object> contentIitem1 = new HashMap<>();
            contentIitem1.put("key", "会议室");
            contentIitem1.put("value", "402");
            contentIitems.add(contentIitem1);
            Map<String, Object> contentIitem2 = new HashMap<>();
            contentIitem2.put("key", "会议地点");
            contentIitem2.put("value", "广州TIT-402会议室");
            contentIitems.add(contentIitem2);
            Map<String, Object> contentIitem3 = new HashMap<>();
            contentIitem3.put("key", "会议时间");
            contentIitem3.put("value", "2018年8月1日 09:00-09:30");
            contentIitems.add(contentIitem3);
            Map<String, Object> contentIitem4 = new HashMap<>();
            contentIitem4.put("key", "参与人员");
            contentIitem4.put("value", "system");
            contentIitems.add(contentIitem4);
            miniProgram.put("content_item", contentIitems);
            param.put("miniprogram_notice", miniProgram);
        }
        return param;
    }

    private String buildContent(MessageConfiguration mc) {
        SystemParameter sp = parameterDao.getParameterByName(SystemConstants.CURRENT_SYSTEM_IP);
        if (ObjectUtils.isEmpty(sp)) {
            throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR);
        }
        String url = sp.getValue() + MessagePushBusinessEnum.getMenuUrlByValue(mc.getBusinessType()) + "/" + mc.getBusinessId();
        return url;
    }

    private String buildUrl(MessageConfiguration mc) {
        SystemParameter sp;
        if (mc.getTerminal() == 2) {
            sp = parameterDao.getParameterByName(SystemConstants.MOBILE_SYSTEM_IP);
        } else {
            sp = parameterDao.getParameterByName(SystemConstants.CURRENT_SYSTEM_IP);
        }
        if (ObjectUtils.isEmpty(sp)) {
            throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR);
        }
//        String jumpUrl = sp.getValue() + MessagePushBusinessEnum.getMenuUrlByValue(mc.getBusinessType()) + "?id=" + mc.getBusinessId();
//        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxcce3fac4a3c8b78c&redirect_uri=" + jumpUrl + "&response_type=code&scope=SCOPE";
        String url = sp.getValue() + MessagePushBusinessEnum.getMenuUrlByValue(mc.getBusinessType()) + "?id=" + mc.getBusinessId();
        return url;
    }
}
